package com.wang.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.common.model.dto.PageResponseResult;
import com.wang.common.model.dto.ResponseResult;
import com.wang.common.model.enums.AppHttpCodeEnum;
import com.wang.util.WmThreadLocalUtil;
import com.wang.wemedia.api.model.dto.WmMaterialDto;
import com.wang.wemedia.api.model.pojo.WmMaterial;
import com.wang.wemedia.mapper.WmMaterialMapper;
import com.wang.wemedia.service.WmMaterialService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ClassUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * @author: wangning
 * @date: 2024/1/11 18:24
 */
@Slf4j
@Service
@Transactional
@RequiredArgsConstructor
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

//    /**
//     * 素材图片的本地上传路径
//     */
//    @Value(value = "${picture.upload.path}")
//    private String srcPath;

    /**
     * 素材图片上传
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) throws FileNotFoundException {

        //1.检查参数
        if(multipartFile == null || multipartFile.getSize() == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.上传图片
        String fileName = UUID.randomUUID().toString().replace("-", "");
        //aa.jpg
        String originalFilename = multipartFile.getOriginalFilename();
        // 获取文件后缀
        String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));
        if (!(".jpg".equals(postfix) || ".png".equals(postfix))) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_IMAGE_FORMAT_ERROR);
        }
        String path = ResourceUtils.getURL("classpath:static/").getPath();
        try {
            // 上传到编译文件的静态目录
            multipartFile.transferTo(new File(path + fileName + postfix));
            // 上传到本地文件的静态目录
//            multipartFile.transferTo(new File(srcPath + fileName + postfix));
            log.info("图片素材上传成功，路径：{}", path + fileName + postfix);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("WmMaterialServiceImpl-上传文件失败");
        }
        // 这里转换为编译文件的类路径确保图片访问的到
        String url = "http://localhost:8081/" + fileName + postfix;
        //3.保存到数据库中
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
        wmMaterial.setUrl(url);
        wmMaterial.setIsCollection((short)0);
        wmMaterial.setType((short)0);
        wmMaterial.setCreatedTime(new Date());
        baseMapper.insert(wmMaterial);
        //4.返回结果
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 素材图片的列表展示
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        // 页码，页数检查，页码最小为0，页数默认为10
        dto.checkParam();
        //2.分页查询
        IPage page = new Page(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //是否收藏
        if(dto.getIsCollection() != null && dto.getIsCollection() == 1){
            lambdaQueryWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        //按照用户查询
        lambdaQueryWrapper.eq(WmMaterial::getUserId,WmThreadLocalUtil.getUser().getId());
        //按照时间倒序
        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);
        page = page(page,lambdaQueryWrapper);
        //3.结果返回
        ResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),(int)page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }

}
